package home.contaduria.web;

import home.contaduria.domain.AppRole;
import home.contaduria.domain.Client;
import home.contaduria.domain.ClientState;
import home.contaduria.service.ClientService;

import java.util.EnumSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping(value = "/clients")
@Controller
public class ClientController {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	private ClientService clientService;

	@Autowired
	public void setClientService(ClientService clientService) {
		this.clientService = clientService;
	}

	@RequestMapping(method = RequestMethod.POST)
	public String create(@Valid Client client, BindingResult bindingResult, Model uiModel,
			HttpServletRequest httpServletRequest) {
		logger.debug("##############################");
		logger.debug("Invoke create client controller");
		if (bindingResult.hasErrors()) {
			uiModel.addAttribute("client", client);
			return "clients/create";
		}
		client.setState(ClientState.ACTIVE);
		client.setRoles(getDefaultUserRoles());
		clientService.createClient(client);
		return "login";
	}

	private Set<AppRole> getDefaultUserRoles() {
		Set<AppRole> roles = EnumSet.of(AppRole.USER);
		return roles;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String createForm(Model model) {
		logger.debug("##############################");
		logger.debug("Invoke controller");
		model.addAttribute("client", new Client());
		return "clients/create";
	}
}
